from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from django.shortcuts import render,HttpResponse
from django.http.response import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from django.core.paginator import Paginator
from django_filters.rest_framework import DjangoFilterBackend
from .models import *
import uuid
from .ser import *

from PIL import Image
import qrcode
from qrcode.constants import ERROR_CORRECT_H
import random
import io




class RegisterView(APIView):
    '''
        邀请码注册
    '''
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        code = request.data.get('code')
        if code:
            old_user = User.objects.filter(code=code).first()
            if old_user:
                user = User.objects.filter(username=username).first()
                if user:
                    return Response({'code':402,'message':'用户名已存在'})
                else:
                    User.objects.create(username=username,password=password,code=uuid.uuid1())
                    old_user.score += 20
                    old_user.save()
                    return Response({'code':201,'message':'邀请成功'})
            else:
                return Response({'code':401,'message':'邀请码不存在'})
        else:
            user = User.objects.filter(username=username).first()
            if user:
                return Response({'code':403,'message':'用户名已存在'})
            else:
                User.objects.create(username=username,password=password,code=uuid.uuid1())
                return Response({'code':203,'message':'用户注册成功'})


def index(request):
    # 初始化
    qr = qrcode.QRCode(version=20,
                       error_correction=ERROR_CORRECT_H,
                       box_size=3, border=2)
    # 添加自定义文本信息，
    qr.add_data('https://bilibili.com')
    qr.make()   # 创建在内存里
    img = qr.make_image()   # 创建二维码图片

    # imgW, imgH = img.size   # 高宽
    # w1, h1 = map(lambda x: x // 4, img.size)    # 生成缩略图
    # im = Image.open(imgFn)
    # imW, imH = im.size
    # w1 = w1 if w1 < imW else imW
    # h1 = h1 if h1 < imH else imH
    # im = im.resize((w1, h1))
    # # 在二维码上中间位置粘贴自定义图片
    # img.paste(im, ((imgW - w1) // 2, (imgH - h1) // 2))
    buf = io.BytesIO()  # 存入内存
    img.save(buf,'jpeg')
    return HttpResponse(buf.getvalue(),'image/jpeg')



def xTree(datas):
    lists = []
    tree = {}
    parent_id = ''

    for i in datas:
        item = i
        tree[item['id']] = item

    root = None
    for i in datas:
        obj = i
        if not obj['pid']:
            root = tree[obj['id']]
            lists.append(root)
        else:
            parent_id = obj['pid']
            if 'childlist' not in tree[parent_id]:
                tree[parent_id]['childlist'] = []
            tree[parent_id]['childlist'].append(tree[obj['id']])
    return lists


class MytreeView(APIView):
    def get(self,request):
        queryset = Cate.objects.all()
        ser = CateSerializers(queryset,many=True)
        mylist = xTree(ser.data)
        return Response(mylist)



from day3_django.settings import *
import os
import hashlib
def md5_(filename):
    m = hashlib.md5()
    m.update(filename.encode())
    return m.hexdigest()
def ck_upload(request):

    f = request.FILES.get("upload")
    #生成MD5名
    name = md5_(f.name)
    path = os.path.join(STATICFILES_DIRS[0],name)
    with open(path,"wb") as fp:

        fp.write(f.read())

    return JsonResponse({
        #表示上传成功"
        "upload":"true",
        ##拼接上传图片的绝对访问路径
        "url":"http://127.0.0.1:8000/static/" + name
    })




class CkPost(APIView):
    def post(self,request):
        ck_data = request.data.get('data')
        ...
        return Response({'code':200})








